# from threading import Thread
# from threading import Lock
# import time
# lock_A = Lock()
# lock_B = Lock()
#
# class MyThread(Thread):
#
#
#     def run(self):
#         self.f1()
#         self.f2()
#
#     def f1(self):
#
#         lock_A.acquire()
#         print(f'{self.name}拿到 A锁')
#
#         lock_B.acquire()  # 第二个线程抢B锁
#         print(f'{self.name}拿到 B锁')
#         lock_B.release()
#
#         lock_A.release()
#
#     def f2(self):
#
#         lock_B.acquire()
#         print(f'{self.name}拿到 B锁')
#
#         time.sleep(1)  # 第一个线程 睡1秒
#         lock_A.acquire()  # 第一个线程抢A锁
#         print(f'{self.name}拿到 A锁')
#         lock_A.release()
#
#         lock_B.release()
#
#
# if __name__ == '__main__':
#     # for i in range(3):
#     #     t = MyThread()
#     #     t.start()
#     t1 = MyThread()
#     t1.start()
#     t2 = MyThread()
#     t2.start()
#     t3 = MyThread()
#     t3.start()
#     print('主线程')

# 递归锁
# 递归锁是一把锁,锁上有记录,只要acquire一次,锁上就计数1次, acquire2次,锁上就计数2次,
# release1次,减一,
# 只要递归锁计数不为0,其他线程不能抢.

from threading import Thread
from threading import Lock
from threading import RLock
import time

# lock_A = RLock()
# lock_B = RLock()
lock_A = lock_B = RLock()

class MyThread(Thread):


    def run(self):
        # lock_A.acquire()
        # lock_B.acquire()
        # print(111)
        # lock_A.release()
        # lock_B.release()

        self.f1()
        self.f2()

    def f1(self):

        lock_A.acquire()
        print(f'{self.name}拿到 A锁')

        lock_B.acquire()  # 第二个线程抢B锁
        print(f'{self.name}拿到 B锁')
        lock_B.release()

        lock_A.release()

    def f2(self):

        lock_B.acquire()
        print(f'{self.name}拿到 B锁')

        time.sleep(1)  # 第一个线程 睡1秒
        lock_A.acquire()  # 第一个线程抢A锁
        print(f'{self.name}拿到 A锁')
        lock_A.release()

        lock_B.release()


if __name__ == '__main__':
    # for i in range(3):
    #     t = MyThread()
    #     t.start()
    t1 = MyThread()
    t1.start()
    t2 = MyThread()
    t2.start()
    t3 = MyThread()
    t3.start()
    print('主线程')